<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="班级名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="部门状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择部门状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      @cell-dblclick="tabClick"
      :row-class-name="tableRowClassName"
      :cell-class-name="tableCellClassName"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="班级名称" prop="typeName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="部门状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="父id" align="center" prop="parentId" />
      <el-table-column label="班级id" align="center" prop="deptId" />
      <el-table-column label="班主任" align="center">
        <template
          slot-scope="scope"
          v-if="scope.row.deptId.toString().length > 1"
        >
          <div
            v-if="
              scope.row.index === clickRow && scope.column.index === clickCell
            "
          >
            <el-select
              v-model="scope.row.classLeaderName"
              @change="handle(scope.row.classLeaderName, scope.row.deptId)"
              @click.native="levelChange(scope.row)"
              clearable
            >
              <el-option
                v-for="(val, index) in teachers"
                :key="index"
                :label="val.teacherName"
                :value="val.teacherName"
              ></el-option>
            </el-select>
          </div>
          <div v-else>{{ scope.row.classLeaderName }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改班级创建管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父id" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="typeOptions"
            :normalizer="normalizer"
            placeholder="请选择父id"
          />
        </el-form-item>
        <el-form-item label="班级id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入班级id" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  getType,
  delType,
  addType,
  updateType,
  listTeachers,
  editClassLeaderName,
} from "@/api/class/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Type",
  dicts: ["sys_normal_disable"],
  components: {
    Treeselect,
  },
  data() {
    return {
      clickRow: null, // 当前点击的行
      clickCell: null, // 当前点击的列
      tabClickLabel: "", // 当前点击的列名
      teachers: {},
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 班级创建管理表格数据
      typeList: [],
      // 班级创建管理树选项
      typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 班级id时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        typeName: undefined,
        createTime: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        typeId: [
          { required: true, message: "编号(id)不能为空", trigger: "blur" },
        ],
        typeName: [
          { required: true, message: "班级名称不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "部门状态不能为空", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "父id不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "班级id不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    // 控制input显示 row 当前行 column 当前列
    tabClick(row, column, cell, event) {
      var that = this;
      switch (column.label) {
        case "班主任":
          that.clickRow = row.index;
          that.clickCell = column.index;
          that.tabClickLabel = column.label;
          break;

        default:
          that.clickRow = null;
          that.clickCell = null;
          that.tabClickLabel = "";
          return;
      }
    },
    // 把每一行的索引放进row
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },

    // 把每一列的索引放进column
    tableCellClassName({ column, columnIndex }) {
      column.index = columnIndex;
    },

    // 失去焦点初始化
    inputBlur(row, event, column) {
      var that = this;
      that.clickRow = null;
      that.clickCell = null;
      that.tabClickLabel = "";
    },
    handle(classLeaderName, deptId) {
      if (classLeaderName.search("班主任") != -1) {
        this.$message.error("请不要选择已经是班主任的老师");
        setTimeout(() => {
          this.getList();
        }, 1000);
      } else {
        console.log(classLeaderName, deptId);
        if (classLeaderName === "") {
          classLeaderName = "不要班主任了!";
        }
        editClassLeaderName(deptId, classLeaderName).then((res) => {
          var that = this;
          that.clickRow = null;
          that.clickCell = null;
          that.tabClickLabel = "";
        });
      }
    },
    levelChange(row) {
      listTeachers(row.deptId).then((res) => {
        this.teachers = res;
      });
      //业务处理
    },
    /** 查询班级创建管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && "" != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] =
          this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listType(this.queryParams).then((response) => {
        this.typeList = this.handleTree(response.data, "deptId", "parentId");
        this.loading = false;
      });
    },
    /** 转换班级创建管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.typeName,
        children: node.children,
      };
    },
    /** 查询班级创建管理下拉树结构 */
    getTreeselect() {
      listType().then((response) => {
        console.log(response);
        this.typeOptions = [];
        const data = { deptId: 0, typeName: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "deptId", "parentId");
        this.typeOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        typeId: null,
        typeName: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        isDelete: null,
        remark: null,
        status: "0",

        parentId: null,
        version: null,
        deptId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.deptId) {
        this.form.parentId = row.deptId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加班级创建管理";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.deptId;
      }
      getType(row.typeId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改班级创建管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.typeId != null) {
            updateType(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addType(this.form)
              .then((response) => {
                if (response.msg == "error") {
                  this.$message.error("班级id已经存在,请重新输入！");
                } else {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除班级创建管理编号为"' + row.typeId + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delType(row.typeId);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>